<template>
    <!-- :value="value" -->
    <el-select            :title="multiple? optionData.name : ''"
            ref="select"
            v-model="value"
            placeholder="请选择"
            size="mini"
            clearable
            :disabled="disabled"
            :filterable="filterable"
            :filter-method="filterMethod"
            style="width: 100%;"
            @clear="clear"
            @visible-change="visibleChange"
    >
        <el-option
                ref="option"
                class="tree-select__option"
                :value="optionData.id"
                :label="optionData.name"
        >
            <el-tree
                    ref="tree"
                    class="tree-select__tree"
                    :class="`tree-select__tree--${multiple ? 'checked' : 'radio'}`"
                    :node-key="nodeKey"
                    :data="options"
                    :props="props"
                    :default-expanded-keys="[value]"
                    :show-checkbox="multiple"
                    :highlight-current="!multiple"
                    :expand-on-click-node="multiple"
                    :filter-node-method="filterNode"
                    @node-click="handleNodeClick"
                    @check-change="handleCheckChange"
            ></el-tree>
        </el-option>
    </el-select>
</template>

<script>
    import BaseComp from "./baseComp";

    export default {
        name: 'TreeSelect',
        extends: BaseComp,
        model: {
            prop: 'value',
            event: 'change1'
        },
        props: {
            // v-model绑定
            value: {
                type: [String, Number],
                default: ''
            },
            multiple: {
                type: Boolean,
                default: false
            },
            // 树形的数据
            options: {
                type: Array,
                default: function () {
                    return []
                }
            },
            // 每个树节点用来作为唯一标识的属性
            nodeKey: {
                type: [String, Number],
                default: 'id'
            },
            filterable: {
                type: Boolean,
                default: true
            },
            disabled: {
                type: Boolean,
                default: false
            },
            // tree的props配置
            props: {
                type: Object,
                default: function () {
                    return {
                        label: 'label',
                        value: 'value',
                        children: 'children'
                    }
                }
            }
        },
        data() {
            return {
                optionData: {
                    id: '',
                    name: ''
                },
                filterFlag: false
            }
        },
        watch: {
            value: {
                handler(val) {
                    if (!this.isEmpty(val)) {
                        this.init(val)
                    }
                },
                immediate: true
            },
            options: function (val) {
                if (!this.isEmpty(val)) {
                    this.init(this.value)
                }
            }
        },
        created() {},
        methods: {
            // 是否为空
            isEmpty(val) {
                for (let key in val) {
                    return false
                }
                return true
            },
            /**
             * 节点点击事件
             * @param data
             */
            handleNodeClick(data) {
                if (this.multiple) {
                    return
                }
                let valueKey = this.props.value;
                let nameKey = this.props.label;
                this.$set(this.optionData, 'id', data[valueKey]);
                this.$set(this.optionData, 'name', data[nameKey]);
                this.$emit('change1', data[valueKey])
                this.$emit('change', data[valueKey]);
                this.$refs.select.visible = false
            },
            /**
             * 节点多选时，点击事件
             */
            handleCheckChange() {
                const nodes = this.$refs.tree.getCheckedNodes()
                let valueKey = this.props.value;
                let labelKey = this.props.label;
                const value = nodes.map((item) => item[valueKey]).join(',')
                const name = nodes.map((item) => item[labelKey]).join(',');
                this.$set(this.optionData, 'id', value);
                this.$set(this.optionData, 'name', name);
                this.$emit('change1', value)
                this.$emit('change', value);
            },
            init(val) {
                // 多选
                if (this.multiple) {
                    const arr = val.toString().split(',')
                    this.$nextTick(() => {
                        this.$refs.tree.setCheckedKeys(arr)
                        const nodes = this.$refs.tree.getCheckedNodes()
                        const name = nodes.map((item) => item[this.props.label]).join(',');
                        this.$set(this.optionData, 'id', val);
                        this.$set(this.optionData, 'name', name);
                    })
                }
                // 单选
                else {
                    val = val === '' ? null : val
                    this.$nextTick(() => {
                        this.$refs.tree.setCurrentKey(val)
                        if (val === null) {
                            return
                        }
                        const node = this.$refs.tree.getNode(val)
                        const name = this.props.label;
                        this.$set(this.optionData, 'id', val);
                        this.$set(this.optionData, 'name', node.data[name]);
                    })
                }
            },
            visibleChange(e) {
                if (e) {
                    const tree = this.$refs.tree
                    this.filterFlag && tree.filter('')
                    this.filterFlag = false
                    let selectDom = null
                    if(this.multiple) {
                        selectDom = tree.$el.querySelector('.el-tree-node.is-checked')
                    } else {
                        selectDom = tree.$el.querySelector('.is-current')
                    }
                    setTimeout(() => {
                        this.$refs.select.scrollToOption({ $el: selectDom })
                    }, 0)
                }
            },
            clear() {
                this.$emit('change1', '')
                this.$emit('change', "");
            },
            filterMethod(val) {
                this.filterFlag = true
                this.$refs.tree.filter(val)
            },
            filterNode(value, data) {
                if (!value) return true
                const label = this.props.label || 'name'
                return data[label].indexOf(value) !== -1
            }
        }
    }
</script>

<style lang="less">
    .tree-select__option {
        &.el-select-dropdown__item {
            height: auto;
            line-height: 1;
            padding: 0;
            background-color: #fff;
        }
    }
    .tree-select__tree {
        padding: 4px 20px;
        font-weight: 400;
        &.tree-select__tree--radio {
            .el-tree-node.is-current > .el-tree-node__content {
                color: red;
                font-weight: 700;
            }
        }
    }

</style>
